﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace eCompany.Custom_Controls
{
    public partial class big_employee_ctrl : UserControl
    {
        private eObj.company m_company = null;
        private eObj.currency_list m_cl = null;
        private eObj.employee m_emp = null;

        public bool isCollapsed = false;
        private bool isLoading = false;

        private Thread m_LoadEmployeeThread = null;
        private delegate void stopLoadHandler(eApi.apiEmployee apiE);
        private stopLoadHandler stopLoadDelegate;


        public big_employee_ctrl(eObj.company comp, string emp_id, eObj.currency_list cl)
        {
            InitializeComponent();
            stopLoadDelegate = new stopLoadHandler(stopLoadEmployee);
            wageLabelExtended.ValidateValue = this.ValidateWage;
            wageLabelExtended.ReformatValue = this.FormatWage;

            m_company = comp;
            m_cl = cl;
            eManager.eManager eM = new eManager.eManager();
            m_emp = eM.getEmployee(m_company, Guid.Parse(emp_id));
        }

        private void big_employee_ctrl_Load(object sender, EventArgs e)
        {
            //SetCollapseState(isCollapsed);
            RefreshEmployee();
        }

        private void RefreshEmployee()
        {
            eManager.eManager eM = new eManager.eManager();

            if (m_emp.fireable == false)
            {
                wageLabelExtended.Visible = false;
                fireCmd.Visible = false;
            }

            namelabelExtended.TextLabel = m_emp.name;
            if (m_emp.locked == true)
            {
                namelabelExtended.LabelForeColor = Color.Red;
                namelabelExtended.Locked = false;
            }
            else
            {
                namelabelExtended.LabelForeColor = Color.Black;
                namelabelExtended.Locked = true;
            }

            wageLabelExtended.TextExtension = eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency;
            wageLabelExtended.Locked = false;
            double wage = eM.getEmployeeSalary(m_emp) * 8;
            wageLabelExtended.TextLabel = eManager.eManager.formatDouble(wage);
            if (wage == 0)
                wageLabelExtended.LabelForeColor = Color.Red;
            else
                wageLabelExtended.LabelForeColor = Color.Black;
            
            eObj.work w = eM.getEmployeeLastWork(m_company, m_emp);
            if (w != null)
            {
                workProdTxt.Text = w.productivity.ToString();
                workProdToolTip.SetToolTip(workProdTxt, "This is the last productivity of the employee");

                eObj.stock s = eM.getStock(m_company, m_emp, w.date);
                double last_shop_price = eM.getShopPrice(m_company);

                lastCLbl.Text = "Last C : " + eManager.eManager.formatDouble(s.production_cost) + eM.getAccount(m_company, Guid.Parse(m_company.default_account)).currency;
                if (last_shop_price < s.production_cost)
                {
                    lastCLbl.BackColor = Color.Red;
                    lastCLbl.ForeColor = Color.White;
                    warningPB.Visible = true;
                    looseMoneyToolTip.SetToolTip(lastCLbl, "You loose money with this guy !");
                    looseMoneyToolTip.SetToolTip(warningPB,"You loose money with this guy !");
                }
                else
                {
                    lastCLbl.BackColor = Color.Transparent;
                    lastCLbl.ForeColor = Color.Green;
                    warningPB.Visible = false;
                    looseMoneyToolTip.RemoveAll();
                }

                lastPLbl.Text = "Last P : " + w.productivity.ToString();

                if (w.date == DateTime.Today)
                {
                    lastWLbl.Text = "Last W : Today";
                    lastWLbl.BackColor = Color.Transparent;
                    lastWLbl.ForeColor = Color.Green;

                    workCmd.Enabled = false;
                }
                else if (w.date == DateTime.Today.AddDays(-1))
                {
                    lastWLbl.Text = "Last W : Yesterday";
                    lastWLbl.BackColor = Color.Transparent;
                    lastWLbl.ForeColor = Color.Orange;
                }
                else
                {
                    lastWLbl.Text = "Last W : " + w.date.ToString("d");
                    lastWLbl.BackColor = Color.Transparent;
                    lastWLbl.ForeColor = Color.Red;
                }
            }
            else
            {
                workProdTxt.Text = "";
                lastWLbl.Text = "Last W : Never !";
                lastWLbl.BackColor = Color.Red;
                lastWLbl.ForeColor = Color.White;

                lastPLbl.Text = "Last P : N/A";
                lastCLbl.Text = "Last C : N/A";
            }

            if (m_LoadEmployeeThread == null)
            {
                isLoading = true;
                if (isCollapsed == true)
                {
                    loaderPB.Image = pics.LOADER_SMALL;
                    loaderPB.Visible = true;
                }
                else
                {
                    // not collapsed
                    loaderPB.Visible = false;
                    avatarPict.Image = pics.LOADER;
                }
                m_LoadEmployeeThread = new Thread(loadEmployeeProc);
                m_LoadEmployeeThread.Start(m_emp);
            }

            RefreshEmployeeGraph();
        }
        private void RefreshEmployeeGraph()
        {
            eManager.eManager eM = new eManager.eManager();

            employeeChart.Series[0].Points.Clear();
            employeeChart.Series[1].Points.Clear();

            List<eCompany.eManager.ChartItem> lst = eM.getEmployeeProductivityChartValue(m_company, m_emp);

            foreach (eCompany.eManager.ChartItem ci in lst)
            {
                employeeChart.Series[0].Points.AddXY(ci.date, ci.volume);
            }

            lst = eM.getEmployeeProductChartValue(m_company, m_emp);
            foreach (eCompany.eManager.ChartItem ci in lst)
            {
                employeeChart.Series[1].Points.AddXY(ci.date, ci.volume);
            }
        }

        private void loadEmployeeProc(object o)
        {
            eObj.employee emp = (eObj.employee)o;
            eApi.api api = new eApi.api();
            try
            {
                eApi.apiEmployee apiE;

                if (emp.api_id != null && emp.api_id != "")
                    apiE = api.loadCitizenFromWeb(emp.api_id, "");
                else
                    apiE = api.loadCitizenFromWeb("", emp.name);
                try
                {
                    this.Invoke(this.stopLoadDelegate, new Object[] { apiE });
                }
                catch (Exception ex)
                {
                    //
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error loading employee : " + ex.Message);
                try
                {
                    this.Invoke(this.stopLoadDelegate, new Object[] { null });
                }
                catch (Exception _ex)
                { }
                //MessageBox.Show("Error loading company : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void stopLoadEmployee(eApi.apiEmployee apiE)
        {
            if (apiE != null)
            {
                avatarPict.ImageLocation = apiE.avatar_link;
                avatarPict.BackgroundImage = null;
                loaderPB.Image = null;
                lvlLbl.Text = apiE.level;
                healthLbl.Text = apiE.wellness;
                namelabelExtended.TextLabel = apiE.name;

                //To get employee api id if we don't have
                m_emp.api_id = apiE.id;
                m_emp.name = apiE.name;
            }
            else
            {
                avatarPict.InitialImage = null;
                avatarPict.Image = null;
                loaderPB.Image = null;
                lvlLbl.Text = "N/A";
                healthLbl.Text = "N/A";
                if (namelabelExtended.TextLabel == "")
                    namelabelExtended.TextLabel = "N/A";
            }
            isLoading = false; 
        }

        private void workCmd_Click(object sender, EventArgs e)
        {
            eCompany.eManager.eManager eM = new eManager.eManager();

            int prod = Convert.ToInt32(workProdTxt.Text);
            DateTime dt = DateTime.Today;
            eM.workEmployee(m_company, m_emp, dt, 8, prod/*, prod*/);

            RefreshEmployee();
        }

        private void workProdTxt_TextChanged(object sender, EventArgs e)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

            string str = workProdTxt.Text;
            str = str.Replace(",", ".");
            double val = 0;
            if (double.TryParse(str, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out val) == true)
                workCmd.Enabled = true;
            else
                workCmd.Enabled = false;
        }

        private void fireCmd_Click(object sender, EventArgs e)
        {
            m_emp.date_out = DateTime.Now;
            this.Enabled = false;
            this.BackColor = Color.LightGray;
            SetCollapseState(true);
        }

        private void workToolStripMenuItem_Click(object sender, EventArgs e)
        {
            eCompany.Forms.work_form f = new Forms.work_form(m_company, m_emp);
            if (f.ShowDialog() == DialogResult.OK)
                RefreshEmployee();
        }

        public void SetCollapseState(bool bCollapsed)
        {
            if (bCollapsed == true)
            {
                this.Height = 31;
                collapsePB.Image = pics.arrow_collapse;

                avatarPict.Visible = false;
                if (isLoading)
                    loaderPB.Visible = true;
                isCollapsed = true;
            }
            else
            {
                this.Height = 92;
                collapsePB.Image = pics.arrow_expand;

                avatarPict.Visible = true;
                loaderPB.Visible = false;
                if (isLoading)
                    avatarPict.Image = pics.LOADER;
                isCollapsed = false;
            }
        }

        private void collapsePB_Click(object sender, EventArgs e)
        {
            SetCollapseState(!isCollapsed);
        }

        private void setNewWageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string s_new_wage = "";
            if (Tools.InputBox("New wage for " + m_emp.name, "New wage :", ref s_new_wage) == DialogResult.OK)
            {
                System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

                double d_new_wage;
                if (double.TryParse(s_new_wage, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out d_new_wage) == true)
                {
                    eManager.eManager eM = new eManager.eManager();
                    eM.setEmployeeSalary(m_emp, d_new_wage/8);
                    RefreshEmployee();
                }
            }
        }

        public bool ValidateWage(string str)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

            double d_new_wage;
            str = str.Replace(",", ".");
            return double.TryParse(str, System.Globalization.NumberStyles.AllowDecimalPoint, culture, out d_new_wage);
        }

        public string FormatWage(string str)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

            str = str.Replace(",", ".");
            double d_new_wage = double.Parse(str, System.Globalization.NumberStyles.AllowDecimalPoint, culture);
            return eManager.eManager.formatDouble(d_new_wage);
        }

        private void wageLabelExtended_TextChanged(object sender, EventArgs e)
        {
            System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");

            string str = wageLabelExtended.TextLabel.Replace(",", ".");
            double d_new_wage = double.Parse(str, System.Globalization.NumberStyles.AllowDecimalPoint, culture);
            eManager.eManager eM = new eManager.eManager();
            eM.setEmployeeSalary(m_emp, d_new_wage/8);
            RefreshEmployee();
        }

        private void namelabelExtended_TextChanged(object sender, EventArgs e)
        {
            m_emp.name = namelabelExtended.TextLabel;
            if (m_LoadEmployeeThread != null && m_LoadEmployeeThread.ThreadState != ThreadState.Running)
                m_LoadEmployeeThread = null;
            m_emp.locked = false;
            RefreshEmployee();
        }

        private void employeeChart_DoubleClick(object sender, EventArgs e)
        {
            eManager.eManager eM = new eManager.eManager();

            List<eCompany.eManager.ChartItem> lst1 = eM.getEmployeeProductivityChartValue(m_company, m_emp);
            List<eCompany.eManager.ChartItem> lst2 = eM.getEmployeeProductChartValue(m_company, m_emp);

            eCompany.Forms.big_graph_form dlg = new Forms.big_graph_form(lst1, lst2);
            dlg.ShowDialog();
        }
    }
}
